package updown.service.task;

import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import updown.dao.ServerHostDao;
import updown.domain.ServerHost;
import updown.domain.ServiceInfo;
import updown.domain.TaskWrapper;
import updown.service.updown.EurekaService;
import updown.service.updown.LocalService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>Title: com.damai.downupservice.serviceInfo </p>
 * <p>Description:updown: -  </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/5
 * @Version: 1.0
 */
@Slf4j
@Service
public class ServerHostService {

    @Autowired
    private ServerHostDao serverHostDao;

    @Autowired
    private EurekaService eurekaService;

    @Autowired
    private LocalService localService;

    /**
     * 根据 serviceName 查询 servers 集合
     * @param serviceName
     * @return
     */
    public List<ServerHost> getServerByServiceName(String serviceName) {
        ServiceInfo serviceInfo = localService.getByName(serviceName);
        if (serviceInfo == null || serviceInfo.getServerList() == null
                || StringUtil.isEmpty(serviceInfo.getServerList())
                || serviceInfo.getServerList().split(",").length == 0 ){
            log.info("log.info:getServerByServiceName 服务对应的 服务器信息为空:{}",eurekaService);
            return Lists.newArrayList();
        }
        List<String> serverNames = Arrays.asList(serviceInfo.getServerList().split(","));
        ArrayList<ServerHost> servers = Lists.newArrayList();
        serverNames.forEach(hostName->{
             ServerHost serverHost = serverHostDao.getByHostName(hostName);
             if (serverHost == null){
                 return;
             }
             servers.add(serverHost);
        });
        return servers;
    }

    public ServerHost getServerHostName(String hostName) {
        return serverHostDao.getByHostName(hostName);
    }

    public ServerHost getServerHostNameOrIP(String hostOrIP) {
        return serverHostDao.getServerHostNameOrIP(hostOrIP);
    }

    /**
     * 填充服务对应的  服务器列表信息
     * @param taskWrapper
     */
    public void fillServerHosts(TaskWrapper taskWrapper) {
        //1. 根据serviceName 找出对应的服务器列表
        List<ServerHost> serverHosts = getServerByServiceName(taskWrapper.getServiceInfo().getServiceName());
        log.info("log.info:serverHosts :{}", serverHosts);
        if (serverHosts.isEmpty()) {
            log.info("fillServerHosts 找不到服务对应的列表{}", serverHosts);
            throw new RuntimeException(taskWrapper.getServiceInfo().getServiceName() + ":找不到服务对应的列表");
        }
        taskWrapper.setServerHosts(serverHosts);
    }

    public void add(ServerHost serverHost) {
        serverHostDao.add(serverHost);
    }

    public List<ServerHost> getAll() {
        return serverHostDao.getAll();
    }
}
